package com.jeeplus.modules.sys.service;

import com.jeeplus.common.utils.*;
import com.jeeplus.common.utils.text.HanyuPinyinUtil;
import com.jeeplus.core.DataSourceConfig.DataSource;
import com.jeeplus.core.service.BaseService;
import com.jeeplus.modules.sys.entity.Api;
import com.jeeplus.modules.sys.entity.DataItemDetailEntity;
import com.jeeplus.modules.sys.entity.DataItemEntity;
import com.jeeplus.modules.sys.entity.TreeModel;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.tools.utils.MultiDBUtils;
import com.jeeplus.modules.tools.utils.SpringUtil;
import org.apache.poi.ss.formula.functions.T;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author Administrator
 * @title: ApiService
 * @projectName jeeplus
 * @description: TODO
 * @date 2019/7/19:58
 */
@Service
@Transactional(readOnly = true)
public class ApiTestService extends BaseService {
    private String detailFieldSql;
    private JdbcTemplate jdbcTemplate;
    public ApiTestService(String beanDataSource){
        //jdbcTemplate=(JdbcTemplate)SpringUtil.getApplicationContext().getBean(beanDataSource);
    }
    public class t{
        private int id;
        public void setId(int id){
            this.id=id;
        }
        public int getId(){
            return this.id;
        }
    }

    public List<T> test1(Object obj) throws Exception {
        mapperSql(this,"","//select","");
        System.out.println(getMap(new Api()));
       return MultiDBUtils.get("jeeplus").queryList("select * from test", (Class<T>) obj.getClass(),null);
    }

    @Autowired
    DbUtils dbUtils;
    protected JdbcTemplate db = (JdbcTemplate) SpringUtil.getApplicationContext().getBean("db");
    protected Logger logger = LoggerFactory.getLogger(getClass());
    @DataSource(description = "slaveDataSources")
    @Transactional(readOnly = false)
    public int test(int i) {

        //super.mapper.findList(new Api());
        System.out.println(Thread.currentThread().getStackTrace()[1].getMethodName());
        return 0;
    }

    public List<DataItemEntity> GetDataItemEntityList() {
        List<DataItemEntity> dataItemEntityList = new ArrayList<>();
        RowMapper<DataItemEntity> rowMapper = new BeanPropertyRowMapper<DataItemEntity>(DataItemEntity.class);
        dataItemEntityList = db.query("SELECT\n" +
                "\tt.F_ItemId,\n" +
                "\tt.F_ParentId,\n" +
                "\tt.F_ItemCode,\n" +
                "\tt.F_ItemName,\n" +
                "\tt.F_IsTree,\n" +
                "\tt.F_IsNav,\n" +
                "\tt.F_SortCode,\n" +
                "\tt.F_DeleteMark,\n" +
                "\tt.F_EnabledMark,\n" +
                "\tt.F_Description,\n" +
                "\tt.F_CreateDate,\n" +
                "\tt.F_CreateUserId,\n" +
                "\tt.F_CreateUserName,\n" +
                "\tt.F_ModifyDate,\n" +
                "\tt.F_ModifyUserId,\n" +
                "\tt.F_ModifyUserName \n" +
                "FROM\n" +
                "\tLR_Base_DataItem t \n" +
                "WHERE\n" +
                "\tt.F_DeleteMark = 0 \n" +
                "ORDER BY\n" +
                "\tt.F_ParentId,\n" +
                "\tt.F_SortCode", rowMapper);
        return dataItemEntityList;
    }

    public List<TreeModel> GetClassifyList() {
        List<TreeModel> treeList = new ArrayList<>();
        List<Map<String, Object>> list = db.queryForList("SELECT\n" +
                "\tt.F_ItemId,\n" +
                "\tt.F_ParentId,\n" +
                "\tt.F_ItemCode,\n" +
                "\tt.F_ItemName,\n" +
                "\tt.F_IsTree,\n" +
                "\tt.F_IsNav,\n" +
                "\tt.F_SortCode,\n" +
                "\tt.F_DeleteMark,\n" +
                "\tt.F_EnabledMark,\n" +
                "\tt.F_Description,\n" +
                "\tt.F_CreateDate,\n" +
                "\tt.F_CreateUserId,\n" +
                "\tt.F_CreateUserName,\n" +
                "\tt.F_ModifyDate,\n" +
                "\tt.F_ModifyUserId,\n" +
                "\tt.F_ModifyUserName \n" +
                "FROM\n" +
                "\tLR_Base_DataItem t \n" +
                "WHERE\n" +
                "\tt.F_DeleteMark = 0 \n" +
                "ORDER BY\n" +
                "\tt.F_ParentId,\n" +
                "\tt.F_SortCode");
        for (Map<String, Object> m : list) {
            TreeModel node = new TreeModel();
            node.id = m.get("F_ItemId").toString();
            node.text = m.get("F_ItemName").toString();
            node.value = m.get("F_ItemCode").toString();
            node.showcheck = false;
            node.checkstate = 0;
            node.isexpand = true;
            node.parentId = m.get("F_ParentId").toString();
            treeList.add(node);
        }
        return treeList;
    }

    public List<DataItemDetailEntity> GetDetailList(String itemCode) {
        RowMapper<DataItemDetailEntity> rowMapper = new BeanPropertyRowMapper<DataItemDetailEntity>(DataItemDetailEntity.class);
        List<DataItemDetailEntity> listDetail = db.query("SELECT\n" +
                "\tt.F_ItemDetailId,\n" +
                "\tt.F_ItemId,\n" +
                "\tt.F_ParentId,\n" +
                "\tt.F_ItemCode,\n" +
                "\tt.F_ItemName,\n" +
                "\tt.F_ItemValue,\n" +
                "\tt.F_QuickQuery,\n" +
                "\tt.F_SimpleSpelling,\n" +
                "\tt.F_IsDefault,\n" +
                "\tt.F_SortCode,\n" +
                "\tt.F_DeleteMark,\n" +
                "\tt.F_EnabledMark,\n" +
                "\tt.F_Description,\n" +
                "\tt.F_CreateDate,\n" +
                "\tt.F_CreateUserId,\n" +
                "\tt.F_CreateUserName,\n" +
                "\tt.F_ModifyDate,\n" +
                "\tt.F_ModifyUserId,\n" +
                "\tt.F_ModifyUserName \n" +
                "FROM\n" +
                "\tLR_Base_DataItemDetail t\n" +
                "\tINNER JOIN LR_Base_DataItem t2 ON t.F_ItemId = t2.F_ItemId \n" +
                "WHERE\n" +
                "\tt.F_DeleteMark = 0 \n" +
                "\t and t2.F_ItemCode ='" + itemCode + "'" +
                "ORDER BY\n" +
                "\tt.F_SortCode", rowMapper);
        return listDetail;
    }

    public List<Map<String, Object>> GetClassifyList(String itemCode) {
        return db.queryForList(MessageFormat.format("SELECT t.* FROM LR_Base_DataItem t WHERE t.F_DeleteMark = 0 and t.F_ITEMCODE=''{0}'' Order By t.F_ParentId,t.F_SortCode", itemCode));
    }

    @Transactional(readOnly = false)
    public boolean SaveDetailEntity(String keyValue, String itemCode, DataItemDetailEntity entity) {
        try {
            String chkSql=MessageFormat.format("SELECT count(*) FROM `lr_base_dataitemdetail` where F_ITEMDETAILID=''{0}''",keyValue);
            if(db.queryForObject(chkSql,Integer.class)>0)
            {
                String updSql=MessageFormat.format("update lr_base_dataitemdetail set F_ItemName=''{1}'',F_ItemValue=''{2}'',F_SortCode=''{3}'',F_EnabledMark=''{4}'',F_Description=''{5}'' where F_ITEMDETAILID=''{0}''",
                        keyValue,entity.F_ItemName,entity.F_ItemValue,entity.F_SortCode,entity.F_EnabledMark,entity.F_Description);
                db.update(updSql);
                return true;
            }
            List<Map<String, Object>> list = GetClassifyList(itemCode);
            for (Map<String, Object> m : list) {
                if (!m.get("F_ISTREE").equals(1) && entity.F_ParentId.isEmpty()) {
                    entity.F_ParentId = "0";

                } else {
                    entity.F_ParentId = m.get("F_ITEMID").toString();
                }
                entity.F_ItemId = m.get("F_ITEMID").toString();
            }
            entity.F_ItemDetailId = IdGen.randomBase62(20);
            String userId = UserUtils.getUser().getId();
            String userName = UserUtils.getUser().getName();
            entity.setF_CreateUserId(userId);
            entity.setF_CreateUserName(userName);
            entity.setF_ModifyUserId(userId);
            entity.setF_ModifyUserName(userName);
            entity.F_SimpleSpelling = new HanyuPinyinUtil().getPinYinFirstLetter(entity.F_ItemName);
            String sql = MessageFormat.format("insert into lr_base_dataitemdetail (F_ItemDetailId,F_ItemId,F_ParentId,F_ItemName,F_IsDefault,F_SortCode,F_DeleteMark,F_EnabledMark,F_Description,F_ItemValue,F_SimpleSpelling,F_ITEMCODE,F_QUICKQUERY,F_CREATEDATE,F_CREATEUSERID,F_CREATEUSERNAME,F_MODIFYDATE,F_MODIFYUSERID,F_MODIFYUSERNAME)\n" +
                            " values(''{0}'',''{1}'',''{2}'',''{3}'',{4},{5},{6},{7},''{8}'',''{9}'',''{10}'',''{11}'',''{12}'',now(),''{13}'',''{14}'',now(),''{15}'',''{16}'')",
                    entity.F_ItemDetailId, entity.F_ItemId, entity.F_ParentId, entity.F_ItemName, entity.F_IsDefault, entity.F_SortCode, entity.F_DeleteMark, entity.F_EnabledMark, entity.F_Description,
                    entity.F_ItemValue, entity.F_SimpleSpelling, entity.F_ItemCode, entity.F_QuickQuery, entity.F_CreateUserId, entity.F_CreateUserName, entity.F_ModifyUserId, entity.F_ModifyUserName);
            //System.out.println(sql);
            db.execute(sql);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
        }
        return false;
    }

    @Transactional(readOnly = false)
    public boolean DeleteDetailForm(String keyValue) {
        try {
            String sql = MessageFormat.format("update  lr_base_dataitemdetail set F_DeleteMark=1 where F_ITEMDETAILID=''{0}''", keyValue);
            db.update(sql);
            return true;
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        return false;
    }

    @Transactional(readOnly = false)
    public boolean SaveClassifyForm(String keyValue, DataItemEntity entity) {
        try {
            String chkSql=MessageFormat.format("select count(*) from LR_Base_DataItem where F_ITEMID=''{0}''",keyValue);
            if(db.queryForObject(chkSql,Integer.class)>0)
            {
                String updSql=MessageFormat.format("update LR_Base_DataItem set F_ItemName=''{1}'',F_ItemCode=''{2}'',F_SortCode=''{3}'',F_IsTree=''{4}'',F_EnabledMark=''{5}'',F_Description=''{6}'' where F_ITEMID=''{0}''",
                        keyValue,entity.F_ItemName,entity.F_ItemCode,entity.F_SortCode,entity.F_IsTree,entity.F_EnabledMark,entity.F_Description);
                db.update(updSql);
                return true;
            }
            entity.F_ItemId = IdGen.randomBase62(20);
            String userId = UserUtils.getUser().getId();
            String userName = UserUtils.getUser().getName();
            entity.setF_CreateUserId(userId);
            entity.setF_CreateUserName(userName);
            entity.setF_ModifyUserId(userId);
            entity.setF_ModifyUserName(userName);
            String sql = MessageFormat.format("INSERT INTO LR_Base_DataItem (\n" +
                            "\tF_ITEMID,\n" +
                            "\tF_PARENTID,\n" +
                            "\tF_ITEMCODE,\n" +
                            "\tF_ITEMNAME,\n" +
                            "\tF_ISTREE,\n" +
                            "\tF_ISNAV,\n" +
                            "\tF_SORTCODE,\n" +
                            "\tF_DELETEMARK,\n" +
                            "\tF_ENABLEDMARK,\n" +
                            "\tF_DESCRIPTION,\n" +
                            "\tF_CREATEDATE,\n" +
                            "\tF_CREATEUSERID,\n" +
                            "\tF_CREATEUSERNAME,\n" +
                            "\tF_MODIFYDATE,\n" +
                            "\tF_MODIFYUSERID,\n" +
                            "\tF_MODIFYUSERNAME \n" +
                            ")\n" +
                            "VALUES\n" +
                            "\t(''{0}'',''{1}'',''{2}'',''{3}'',{4},{5},{6},{7},{8},''{9}'',now(),''{10}'',''{11}'',now(),''{12}'',''{13}'')",
                    entity.F_ItemId, entity.getF_ParentId(), entity.F_ItemCode, entity.F_ItemName,
                    entity.F_IsTree, entity.F_IsNav, entity.F_SortCode, entity.F_DeleteMark, entity.F_EnabledMark,
                    entity.F_Description, entity.F_CreateUserId, entity.F_CreateUserName, entity.F_ModifyUserId, entity.F_ModifyUserName);
            db.update(sql);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
        }
        return false;
    }

    @Transactional(readOnly = false)
    public boolean DeleteClassifyForm(String keyValue) {
        try {
            String sql = MessageFormat.format("update LR_Base_DataItem set F_DELETEMARK=1  where F_ITEMID=''{0}''", keyValue);
            db.update(sql);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
        }
        return false;
    }

    public boolean ExistItemCode(String keyValue, String F_ItemCode) {
        List<DataItemEntity> list = GetDataItemEntityList();
        if (keyValue.isEmpty()) {
            for (DataItemEntity m : list) {
                if (m.F_ItemCode.equals(F_ItemCode)) {
                    return false;
                }
            }
        } else {
            for (DataItemEntity m : list) {
                if (m.F_ItemCode.equals(F_ItemCode) && m.F_ItemId.equals(keyValue)) {
                    return false;
                }
            }
        }

        return true;
    }

    public boolean ExistItemName(String keyValue, String itemName) {
        List<DataItemEntity> list = GetDataItemEntityList();
        if (keyValue.isEmpty()) {
            for (DataItemEntity m : list) {
                if (m.F_ItemName.equals(itemName)) {
                    return false;
                }
            }
        } else {
            for (DataItemEntity m : list) {
                if (m.F_ItemName.equals(itemName) && m.F_ItemId.equals(keyValue)) {
                    return false;
                }
            }
        }
        return true;
    }

    public boolean ExistDetailItemName(String keyValue, String F_ItemName, String itemCode) {
        List<DataItemDetailEntity> list = GetDetailList(itemCode);
        if (keyValue.isEmpty()) {
            for (DataItemDetailEntity m : list) {
                if (m.F_ItemName.equals(F_ItemName)) {
                    return false;
                }
            }
        } else {
            for (DataItemDetailEntity m : list) {
                if (m.F_ItemValue.equals(F_ItemName) && m.F_ItemDetailId.equals(keyValue)) {
                    return false;
                }
            }
        }
        return true;
    }

    public boolean ExistDetailItemValue(String keyValue, String F_ItemValue, String itemCode) {
        List<DataItemDetailEntity> list = GetDetailList(itemCode);
        //System.out.println(JsonMapper.toJsonString(list));
        if (keyValue.isEmpty()) {
            for (DataItemDetailEntity m : list) {
                if (m.F_ItemName.equals(F_ItemValue)) {
                    return false;
                }
            }
        } else {
            for (DataItemDetailEntity m : list) {
                if (m.F_ItemValue.equals(F_ItemValue) && m.F_ItemDetailId.equals(keyValue)) {
                    return false;
                }
            }
        }
        return true;
    }
}
